package web;

import beans.LoginStatus;
import beans.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import service.UserService;
import utils.ResultUtils;

import java.io.IOException;

@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取页面传递的参数
        //username=root&password=123456
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2.将页面的参数进行封装,方便将来传递给service层
        User user = new User(username, password);

        //3.调用UserService处理业务逻辑:登录逻辑处理
        UserService userService = new UserService();
        User existUser = userService.login(user);

        //4.根据existUser结果来决定响应的信息
        String responseData;//存储响应数据
        if (existUser != null) {
            //说明已经登录成功
            //a.将用户信息(会话状态)存储中session中
            request.getSession().setAttribute("existUser", existUser);


            //登录成功并且用户勾选了记住我复选框,此时向浏览器写一个cookie
            //该cookie中存储了用户信息
            String autoLogin = request.getParameter("autoLogin");
            if (autoLogin!=null && autoLogin.equals("on")) {
                //说明用户勾选
                String values = user.getUsername() + "#" + user.getPassword();
                Cookie cookie = new Cookie("autoLogin", values);
                cookie.setMaxAge(7 * 24 * 60 * 60);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }

            //b.构造登录成功的响应数据
            responseData = ResultUtils.result(LoginStatus.LOGIN_SUCCESS, existUser);
        } else {
            //说明登录失败,构造登录失败的响应数据
            //new User(username, password)构造的是登录失败的 用户名和密码
            responseData = ResultUtils.result(LoginStatus.LOGIN_FAIL, new User(username, password));
        }
        //5.将统一构造的json数据响应给浏览器
        response.getWriter().write(responseData);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
